<template>
  <div class="add-user">
    <el-form
      :inline="true"
      :rules="rules"
      ref="ruleForm"
      :model="dataForm"
      label-width="120px"
      class="dialog"
      :label-position="labelPosition"
      autocomplete="off"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="登录名称" prop="username">
            <el-input
              v-model="dataForm.username"
              placeholder="请输入登录名称"
              clearable
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="密 码" prop="password">
            <el-input v-model="dataForm.password" placeholder="请输入密码" disabled clearable show-password></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="真实姓名" prop="realName">
            <el-input v-model="dataForm.realName" placeholder="请输入真实姓名" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电子邮箱" prop="mail">
            <el-input v-model="dataForm.mail" placeholder="请输入电子邮箱" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="电话" prop="phone" >
            <el-input v-model="dataForm.phone" placeholder="请输入电话" clearable></el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="组织机构名称" prop="orgName">
            <el-input v-model="dataForm.orgName" placeholder="请输入组织机构名称" clearable></el-input>
          </el-form-item>
        </el-col> -->
        
      <el-col :span="12">
          <el-form-item label="公司组名称">
           <el-select v-model="dataForm.companyCodes" placeholder="请输入公司组名称" remote filterable @change="getCompanVal">
              <el-option
                v-for="item in companList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                clearable
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
           <!-- <el-col :span="12">
          <el-form-item label="用户类型">
            <el-select v-model="userTypeValue" placeholder="请选择" @change="selectUserType">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col> -->

      </el-row>
      <el-row :gutter="20">
         <el-col :span="12">
          <el-form-item label="用户角色">
            <el-select v-model="dataForm.rolesCodes" clearable placeholder="请输入用户角色"  multiple>
              <el-option
                v-for="item in userRole"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="23">
             <el-form-item prop="remark" label="备注">
          <el-input type="textarea" :rows="5" placeholder="请输入备注" clearable v-model="dataForm.remark"></el-input>
        </el-form-item>
        </el-col>
      </el-row>
      <el-form-item style="margin-top:20px;margin-bottom:100px;text-align:center;">
       
        <el-button type="primary" @click="doneFinshed('ruleForm')" :disabled="isDabled">确认</el-button>
         <el-button type="info" @click="backPrev">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import md5 from 'md5'
export default {
  data () {
    var username = (rule, value, callback) => {
      console.log(value)
      // value = value.replace(/[\d]/g, '')
      var regex = /^(([\u4e00-\u9fa5]{2,64})|([a-zA-Z]+\s?[a-zA-Z]+))$/
      if (value == '') {
        callback(new Error('真实姓名不允许为空'))
      } else if (!regex.test(value)) {
        callback(new Error('真实姓名只能输入中文或英文'))
      } else {
        callback()
      }
    }
    var phone = (rule, value, callback) => {
      console.log(value)

      var regex = /^1\d{10}$/
      if (value != '') {
        if (!regex.test(value)) {
          callback(new Error('请输入正确的电话'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      userRole: [],
      options: [],
      userTypeValue: '',
      disabled: false,
      multipleCompany: false,
      dataForm: {
        rolesCodes: '',
        companyCodes: '',
        operateType: '',
        userType: '',
        username: '',
        password: '',
        realName: '',
        mail: '',
        phone: '',
        orgCode: '',
        orgNo: '',
        orgName: '',
        remark: ''

      },

      sysCode: ['sys_role'],
      companList: [],
      roledisabled: true,
      componydisabled: true,
      labelPosition: 'right',
      rules: {
        username: [
          { required: true, trigger: 'blur' },
          { max: 20, message: '长度不可超过20个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不允许为空', trigger: 'blur' },
          { min: 6, max: 100, message: '长度不可超过100个字符', trigger: 'blur' }
        ],
        realName: [
          { validator: username, required: true, trigger: 'blur' },
          { min: 2, max: 10, message: '长度不可超过10个字符', trigger: 'blur' }
        ],

        phone: [
          { validator: phone, required: false, trigger: 'blur', type: 'number' },
          { max: 11, message: '长度不可超过11个字符', trigger: 'blur' }
        ],
        orgName: [
          { required: true, message: '组织机构名称不允许为空', trigger: 'blur' },
          { min: 2, max: 40, message: '长度不可超过40个字符', trigger: 'blur' }
        ],
        companyName: [
          { required: true, message: '公司名称不允许为空', trigger: 'blur' },
          { min: 2, max: 40, message: '长度不可超过40个字符', trigger: 'blur' }
        ],
        mail: [
          { required: false, message: '请输入正确的邮箱', trigger: 'blur', type: 'email' },
          { min: 2, max: 40, message: '长度不可超过40个字符', trigger: 'blur' }
        ],
        remark: [
          { min: 2, max: 40, message: '长度不可超过255个字符', trigger: 'blur' }
        ]
      },
      isDabled: false
    }
  },
  mounted () {
    this.getDictionaryByType()

    if (this.$route.query.code) {
      this.getEditInfo(this.$route.query.code)
    } else {
      this.$router.push('/systemSettings/user/list')
    }
    // this.getRoleOfUser()
    var companyCode = JSON.parse(localStorage.getItem('user_info')).a.companyCode
    console.log(companyCode)
    if (companyCode == null || companyCode == '') {
      this.isShowCompany = true
    } else {
      this.isShowCompany = false
    }
  },

  methods: {
    backPrev () {
      // this.$confirm('此操作将放弃当前修改, 是否继续?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      this.$router.go(-1)
        // })
        // .catch(() => {})
    },
    getEditInfo (code) {
      this.$http.post(`/${this.$const.PREFIX.AUTHORITY}/user/findUserDetail`, {userCode: code}).then((res) => {
        if (res.result) {
          var data = res.data.user
          var roleData = res.data.roles
          var compayList = res.data.companies
          console.log(compayList)

          this.dataForm = {
            username: data.username,
            password: data.password,
            realName: data.realName,
            orgName: data.orgName,
            companyName: data.companyName,
            mail: data.mail,
            phone: data.phone,
            remark: data.remark,
            rolesCodes: [],
            companyCodes: ''
          }

          // var rolesArray = []
          // for (var y in roleData) {
          //   rolesArray.push(roleData[y].code)
          // }
          // this.dataForm.rolesCodes = rolesArray
          this.userTypeValue = data.userType
          this.getRoleOfUser(null, roleData)
          this.getCompanList(data)
          var result = res.data.companies
          if (data.userType === 'sys_user') {
            var delCompaniesData = []
            if (res.result) {
              for (var y in result) {
                delCompaniesData.push(result[y].code)
              }
              // this.getRoleOfUser(this.sysCode)
              this.multipleCompany = true
              this.dataForm.companyCodes = delCompaniesData
            }
          } else {
            if (res.result) {
              console.log(compayList)
              // this.dataForm.companyCodes = compayList[0].code
              // this.getRoleOfUser(result[0].code)
              this.multipleCompany = false
            }
          }
        }
      })
    },
    getDictionaryByType () {
      var data = {
        type: 'userType'
      }
      this.$http.post(`/${this.$const.PREFIX.AUTHORITY}/dictionary/findDictionaryByType`, data).then((res) => {
        var result = res.data
        var delData = []
        if (res.result) {
          for (var k in result) {
            delData.push({value: result[k].dicCode, label: result[k].dicValue})
          }
          this.options = delData
        }
      })
    },
    selectUserType () {
      if (this.userTypeValue === 'sys_user') {
        this.roledisabled = true
        this.componydisabled = false
        this.multipleCompany = true
        this.dataForm.companyCodes = []
        this.getCompanList()
        this.getRoleOfUser(this.sysCode)
      } else {
        this.componydisabled = false
        this.roledisabled = true
        this.multipleCompany = false
        this.dataForm.companyCodes = ''
      }
      this.dataForm.rolesCodes = []
    },
    getCompanList (compayList) {
      var data = {
        companyNo: '',
        name: ''
      }
      this.$http.post(`/${this.$const.PREFIX.AUTHORITY}/companygroups/findCompanyGList`, data).then((res) => {
        var result = res.data
        var delData = []
        if (res.result) {
          for (var k in result) {
            delData.push({value: result[k].code, label: result[k].name})
          }
          this.companList = delData
          if (compayList && compayList != '') {
            // var companitesArray = []
            // for (var i in compayList) {
            //   companitesArray.push(compayList[i].code)
            // }
            this.dataForm.companyCodes = compayList.comGroupCode
            console.log(this.dataForm.companyCodes)
          }
        }
      })
    },
    doneFinshed (formName) {
      console.log(typeof this.dataForm.phone)
      if (this.dataForm.phone != '') {
        var regex = /^1\d{10}$/
        if (!regex.test(this.dataForm.phone)) {
          this.$message.error('请输入正确的电话')
          return
        }
      }
      var companyCodesl = this.dataForm.companyCodes
      if (Array.isArray(this.dataForm.companyCodes)) {
        companyCodesl = this.dataForm.companyCodes
      } else {
        companyCodesl = this.dataForm.companyCodes.split(',')
      }
      var groupName = ''
      for (var k in this.companList) {
        if (this.companList[k].value == this.dataForm.companyCodes) {
          groupName = this.companList[k].label
        }
      }
      var data = {
        rolesCodes: this.dataForm.rolesCodes,
        companyCodes: companyCodesl,
        operateType: 'edit',
        // userType: this.userTypeValue,
        user: {
          username: this.dataForm.username,
          password: md5(this.dataForm.password),
          realName: this.dataForm.realName,
          mail: this.dataForm.mail,
          phone: this.dataForm.phone,
          orgCode: this.dataForm.orgCode,
          orgNo: this.dataForm.orgNo,
          orgName: this.dataForm.orgName,
          remark: this.dataForm.remark,
          code: this.$route.query.code,
          comGroupCode: this.dataForm.companyCodes,
          comGroupName: groupName
        }

      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(this.userTypeValue)
          // if (this.userTypeValue === 'sys_user') {
          //   if (this.dataForm.rolesCodes.length === 0) {
          //     this.$message({
          //       message: '请选择用户角色',
          //       type: 'warning'
          //     })
          //     return
          //   }
          // } else if (this.userTypeValue === 'company_user') {
          //   if (this.dataForm.companyCodes.length === 0) {
          //     this.$message({
          //       message: '请选择公司',
          //       type: 'warning'
          //     })
          //     return
          //   } else
          //   if (this.dataForm.rolesCodes.length === 0) {
          //     this.$message({
          //       message: '请选择用户角色',
          //       type: 'warning'
          //     })
          //     return
          //   }
          // }
          this.$http.post(`/${this.$const.PREFIX.AUTHORITY}/user/operationData`, data).then((res) => {
            if (res.result) {
              this.isDabled = true
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.$router.push('/systemSettings/user/list')
            } else {
              this.isDabled = false
              this.$message.error({
                message: res.msg,
                duration: 5000
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getRoleOfUser (code, roleData) {
      this.$http.post(`/${this.$const.PREFIX.AUTHORITY}/user/findRoleOfUser`, {userCompanyCode: ''}).then((res) => {
        var data = res.data
        var delData = []
        for (var k in data) {
          delData.push({ value: data[k].code, label: data[k].name })
        }

        this.userRole = delData
        if (roleData) {
          var delDatas = []
          for (var y in roleData) {
            delDatas.push(roleData[y].code)
          }
          this.dataForm.rolesCodes = delDatas
        }
      })
    },
    getCompanVal () {
      // if (this.userTypeValue === 'sys_user') {
      //   this.getRoleOfUser(this.dataForm.companyCodes)
      // } else {
      //   this.getRoleOfUser([this.dataForm.companyCodes])
      // }

      // if (this.dataForm.companyCodes.length > 0) {
      //   this.roledisabled = false
      // } else {
      //   this.roledisabled = true
      // }
      // this.dataForm.rolesCodes = []
    }
  }
}
</script>
<style>
.dialog .el-form-item__content {
  width: 70%;
}
.dialog .el-form-item {
  width: 100%;
}
.dialog .el-select {
  width: 100%;
}
.el-form-item__label {
  text-align: right;
}

</style>

<style lang="scss" scoped>
.add-user {
  background: #fff;
  padding-top: 20px;
  padding-left: 20px;
}
</style>

